package com.system.service.impl;

import com.system.mapper.ContractGoodsMapper;
import com.system.mapper.ContractMapper;
import com.system.pojo.Contract;
import com.system.pojo.ContractGoods;
import com.system.service.ContractGoodsService;
import com.system.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yjymm
 * @date 2019-12-19 20:10
 */

@Service
public class ContractGoodsServiceImpl implements ContractGoodsService {

    @Autowired
    private ContractGoodsMapper cgm;

    @Autowired
    private ContractMapper contractMapper;


    @Override
    public ResultVo<ContractGoods> deleteByCidAndCgid(Integer contractId, Integer cgId) {
        ResultVo<ContractGoods> resultVo = new ResultVo<ContractGoods>();
        //重新计算合同的总金额
        Contract contract = contractMapper.selectByPrimaryKey(contractId);
        ContractGoods cg = cgm.selectByPrimaryKey(cgId);
        double money = cg.getPurchaseNum()*cg.getPurchasePrice();
        contract.setMoney(contract.getMoney()-money);
        int i1 = contractMapper.updateByPrimaryKeySelective(contract);
        int i = cgm.deleteByCidAndCgid(cgId);
        if (i == 1 && i1 == 1){
            resultVo.setDelete(true);
            resultVo.setMessage("删除成功");
        }else{
            throw new RuntimeException();
        }
        return resultVo;
    }

    @Override
    public ResultVo<ContractGoods> selectDetailById(Integer cgId) {
        ResultVo<ContractGoods> resultVo = new ResultVo<ContractGoods>();
        ContractGoods cg = cgm.selectByPrimaryKey(cgId);
        if (cg != null){
            resultVo.setT(cg);
            resultVo.setSelect(true);
            resultVo.setMessage("查询成功");
        }else{
            resultVo.setMessage("查询信息失败");
        }
        return resultVo;
    }

    @Override
    public ResultVo<ContractGoods> update(ContractGoods cg) {
        ResultVo<ContractGoods> resultVo = new ResultVo<ContractGoods>();
        Integer contractId = cg.getContractId();
        Contract contract = contractMapper.selectByPrimaryKey(contractId);
        Integer newPurchaseNum = cg.getNewPurchaseNum();
        Integer purchaseNum = cg.getPurchaseNum();
        double price = (newPurchaseNum-purchaseNum)*cg.getPurchasePrice();
        contract.addMoney(price);
        cg.setPurchaseNum(newPurchaseNum);
        cg.setRest(newPurchaseNum);
        //更新合同
        contractMapper.updateByPrimaryKeySelective(contract);
        //更新合同商品表
        cgm.updateByPrimaryKeySelective(cg);
        resultVo.setUpdate(true);
        resultVo.setMessage("更新成功");
        return resultVo;
    }
}
